import React, { useState, useEffect } from 'react';
import { Box, Card, CardContent, Typography, Grid, Chip, Button, Dialog, DialogTitle, DialogContent, DialogActions, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, IconButton, Fab, CircularProgress, Tooltip } from '@mui/material';
import { Add as AddIcon, Visibility as VisibilityIcon, HourglassEmpty as HourglassIcon, CheckCircle as CheckCircleIcon, Cancel as CancelIcon, AlertTriangle, CalendarToday, Clock } from '@mui/icons-material';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { useNavigate } from 'react-router-dom';
import apiRequest from '../utils/api';
import CryptoJS from 'crypto-js';

const MyMaintenanceRecords = () => {
  const navigate = useNavigate();
  const [maintenanceRecords, setMaintenanceRecords] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [openDialog, setOpenDialog] = useState(false);
  const [encryptionInfo, setEncryptionInfo] = useState({ show: false, key: '', algorithm: '' });

  useEffect(() => {
    loadMyMaintenanceRecords();
  }, []);

  const loadMyMaintenanceRecords = async () => {
    try {
      setLoading(true);
      const response = await apiRequest.get('/api/maintenance/my-reports');
      setMaintenanceRecords(response.data);
    } catch (err) {
      console.error('加载维修记录失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status) => {
    const colors = {
      PENDING: 'warning',
      ASSIGNED: 'info',
      IN_PROGRESS: 'primary',
      COMPLETED: 'success',
      CANCELLED: 'error'
    };
    return colors[status] || 'default';
  };

  const getStatusLabel = (status) => {
    const labels = {
      PENDING: '待处理',
      ASSIGNED: '已分配',
      IN_PROGRESS: '处理中',
      COMPLETED: '已完成',
      CANCELLED: '已取消'
    };
    return labels[status] || status;
  };

  const getPriorityColor = (priority) => {
    const colors = {
      LOW: 'success',
      MEDIUM: 'warning',
      HIGH: 'error',
      URGENT: 'error'
    };
    return colors[priority] || 'default';
  };

  const getPriorityLabel = (priority) => {
    const labels = {
      LOW: '低',
      MEDIUM: '中',
      HIGH: '高',
      URGENT: '紧急'
    };
    return labels[priority] || priority;
  };

  const getMaintenanceTypeLabel = (type) => {
    const labels = {
      REGULAR_MAINTENANCE: '定期保养',
      REPAIR: '故障维修',
      EMERGENCY_REPAIR: '紧急维修',
      ABNORMAL_HANDLING: '异常处理'
    };
    return labels[type] || type;
  };

  // 增强的时间格式化函数，解决时区问题
  const formatTimestamp = (timestamp, formatPattern = 'MM/dd HH:mm') => {
    if (!timestamp) return '';
    
    try {
      // 尝试多种方式解析日期
      let date;
      
      // 记录原始时间戳以便调试
      console.log('Processing timestamp:', timestamp, 'Type:', typeof timestamp);
      
      // 1. 如果是数组类型，尝试解析为日期
      if (Array.isArray(timestamp) && timestamp.length >= 3) {
        // 处理数组格式的日期 [年, 月, 日, 时, 分, 秒, 毫秒]
        const year = timestamp[0];
        // 检查月份是否可能从1开始，如果小于13则认为是Java格式
        const month = timestamp[1] < 13 ? timestamp[1] - 1 : timestamp[1];
        const day = timestamp[2];
        const hour = timestamp[3] || 0;
        const minute = timestamp[4] || 0;
        const second = timestamp[5] || 0;
        const ms = timestamp[6] || 0;
        
        date = new Date(year, month, day, hour, minute, second, ms);
        console.log('Created date from array:', date);
      }
      // 2. 如果是对象类型，尝试获取其值
      else if (typeof timestamp === 'object' && timestamp !== null) {
        // 尝试从对象中提取日期值
        const dateValue = timestamp.value || timestamp.toString();
        console.log('Extracted date value:', dateValue);
        date = new Date(dateValue);
      } else {
        // 3. 处理字符串类型的时间戳，特别关注Java LocalDateTime转换的问题
        if (typeof timestamp === 'string') {
          // 检查是否为没有时区信息的ISO格式 (Java LocalDateTime转换后)
          if (timestamp.includes('T') && !timestamp.includes('Z') && !timestamp.match(/[+-]\d{2}:?\d{2}$/)) {
            // 这种格式通常是Java LocalDateTime直接转换的，需要特别处理时区
            // 假设服务器返回的时间是UTC时间，需要转换为本地时间
            console.log('Java LocalDateTime format detected:', timestamp);
            // 方法1: 假设时间是UTC时间，添加UTC时区标记
            const utcTimestamp = `${timestamp}Z`;
            date = new Date(utcTimestamp);
            console.log('Converted to UTC date:', date);
          } else {
            // 直接尝试Date构造函数
            date = new Date(timestamp);
          }
        } else {
          // 其他类型直接尝试转换
          date = new Date(timestamp);
        }
      }
      
      // 3. 如果是LocalDateTime格式(2025-09-03T12:00)且之前解析失败
      if (isNaN(date.getTime()) && typeof timestamp === 'string' && timestamp.includes('T')) {
        // 添加完整的时区信息
        const adjustedTimestamp = timestamp.includes('+') ? timestamp : `${timestamp}+00:00`;
        console.log('Adjusted timestamp for LocalDateTime:', adjustedTimestamp);
        date = new Date(adjustedTimestamp);
      }
      
      // 4. 如果是LocalDate格式(2025-09-03)
      if (isNaN(date.getTime()) && typeof timestamp === 'string' && timestamp.match(/^\d{4}-\d{2}-\d{2}$/)) {
        // 添加默认时间和时区
        const adjustedTimestamp = `${timestamp}T12:00:00+00:00`;
        console.log('Adjusted timestamp for LocalDate:', adjustedTimestamp);
        date = new Date(adjustedTimestamp);
      }
      
      // 5. 如果是带有特殊格式的日期字符串
      if (isNaN(date.getTime()) && typeof timestamp === 'string') {
        // 尝试其他可能的格式
        const formats = [
          /^(\d{4})-(\d{2})-(\d{2})$/ // YYYY-MM-DD
        ];
        
        for (let i = 0; i < formats.length && isNaN(date.getTime()); i++) {
          if (formats[i].test(timestamp)) {
            console.log('Matched format pattern:', formats[i].toString());
            date = new Date(timestamp);
            break;
          }
        }
      }
      
      // 检查是否解析成功
      if (isNaN(date.getTime())) {
        console.error('Failed to parse timestamp:', timestamp);
        return '-';
      }
      
      // 格式化日期
      console.log('Successfully parsed date:', date);
      return format(date, formatPattern, { locale: zhCN });
    } catch (error) {
      console.error('Error formatting timestamp:', error, 'Timestamp:', timestamp);
      return '-';
    }
  };

  const handleViewDetails = (record) => {
    setSelectedRecord(record);
    setOpenDialog(true);
  };

  // 生成随机密钥 (128位 = 16字节 (32个十六进制字符))
  const generateRandomKey = () => {
    const chars = '0123456789abcdef';
    let key = '';
    for (let i = 0; i < 32; i++) {
      key += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return key;
  };

  // AES128位加密函数
  const encryptWithAES = (data, key) => {
    // 生成16字节的初始化向量
    const iv = CryptoJS.lib.WordArray.random(16);
    // 注意：将十六进制密钥转换为WordArray
    const keyWordArray = CryptoJS.enc.Hex.parse(key);
    // 使用AES-CBC模式加密
    const encrypted = CryptoJS.AES.encrypt(data, keyWordArray, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    // 返回加密数据和IV的Base64编码
    return {
      ciphertext: encrypted.toString(),
      iv: iv.toString()
    };
  };

  // 复制文本到剪贴板
  const copyToClipboard = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      // 显示复制成功的临时提示
      alert('密钥已复制到剪贴板！');
    } catch (err) {
      console.error('复制到剪贴板失败:', err);
      alert('复制失败，请手动复制密钥');
    }
  };

  // 关闭加密信息对话框
  const handleCloseEncryptionDialog = () => {
    setEncryptionInfo({ show: false, key: '', algorithm: '' });
  };

  // 导出维修数据并进行AES128位加密
  const exportMaintenanceData = async () => {
    try {
      // 获取用户基础数据
      const userDataResponse = await apiRequest.get('/api/users/me');
      const userData = userDataResponse.data;
      
      // 获取所有相关车辆的详细信息
      const vehicleIds = [...new Set(maintenanceRecords.map(record => record.vehicleId))];
      const vehicleDetailsMap = {};
      
      // 并行获取所有车辆的详细信息
      await Promise.all(
        vehicleIds.map(async (vehicleId) => {
          try {
            const vehicleResponse = await apiRequest.get(`/api/vehicles/${vehicleId}`);
            vehicleDetailsMap[vehicleId] = vehicleResponse.data;
          } catch (error) {
            console.warn(`获取车辆ID ${vehicleId} 的详细信息失败:`, error);
            // 使用基础信息作为备选
            const record = maintenanceRecords.find(r => r.vehicleId === vehicleId);
            vehicleDetailsMap[vehicleId] = {
              licensePlate: record?.vehiclePlate || '未知',
              brand: '未知',
              model: '未知',
              year: '未知'
            };
          }
        })
      );
      
      // 准备导出内容
      let exportContent = '===== 用户基础数据 =====\n';
      exportContent += `用户ID: ${userData.id || '未知'}\n`;
      exportContent += `用户名: ${userData.username || '未知'}\n`;
      exportContent += `角色: ${userData.role || '未知'}\n`;
      exportContent += `创建时间: ${userData.createdAt ? formatTimestamp(userData.createdAt, 'yyyy年MM月dd日 HH:mm') : '未知'}\n\n`;
      
      exportContent += '===== 维修数据表单 =====\n';
      maintenanceRecords.forEach((record, index) => {
        // 获取车辆详细信息
        const vehicleDetails = vehicleDetailsMap[record.vehicleId];
        
        exportContent += `\n--- 维修记录 ${index + 1} --->\n`;
        exportContent += `车辆信息: ${record.vehiclePlate}\n`;
        // 车辆详细信息
        exportContent += `  品牌: ${vehicleDetails?.brand || '未知'}\n`;
        exportContent += `  型号: ${vehicleDetails?.model || '未知'}\n`;
        exportContent += `  年份: ${vehicleDetails?.year || '未知'}\n`;
        exportContent += `  车辆类型: ${vehicleDetails?.vehicleType || '未知'}\n`;
        exportContent += `  燃油类型: ${vehicleDetails?.fuelType || '未知'}\n`;
        if (vehicleDetails?.mileage) {
          exportContent += `  里程数: ${vehicleDetails.mileage} km\n`;
        }
        if (vehicleDetails?.lastMaintenance) {
          exportContent += `  上次保养: ${formatTimestamp(vehicleDetails.lastMaintenance, 'yyyy年MM月dd日')}\n`;
        }
        // 维修记录原有信息
        exportContent += `异常类型: ${getMaintenanceTypeLabel(record.maintenanceType)}\n`;
        exportContent += `优先级: ${getPriorityLabel(record.priority)}\n`;
        exportContent += `状态: ${getStatusLabel(record.status)}\n`;
        exportContent += `服务商: ${record.serviceProviderName || '未分配'}\n`;
        exportContent += `报告时间: ${record.reportedAt ? formatTimestamp(record.reportedAt, 'yyyy年MM月dd日 HH:mm') : '未知'}\n`;
        exportContent += `异常描述: ${record.description}\n`;
        if (record.location) exportContent += `发生位置: ${record.location}\n`;
        if (record.estimatedCost) exportContent += `预估费用: ¥${record.estimatedCost}\n`;
        if (record.notes) exportContent += `备注: ${record.notes}\n`;
        if (record.tags && record.tags.length > 0) {
          exportContent += `标签: ${record.tags.join(', ')}\n`;
        }
      });
      
      // 生成随机密钥
      const secretKey = generateRandomKey();
      
      // 使用AES128位加密数据
      const encryptionResult = encryptWithAES(exportContent, secretKey);
      
      // 构建加密文件内容
      const encryptedFileContent = `AES-128-CBC 加密数据\n` +
                                   `IV: ${encryptionResult.iv}\n` +
                                   `加密内容:\n` +
                                   encryptionResult.ciphertext;
      
      // 创建下载链接
      const blob = new Blob([encryptedFileContent], { type: 'text/plain;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `加密维修记录_${format(new Date(), 'yyyy-MM-dd_HH-mm-ss')}.txt`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
      // 设置加密信息并显示带复制按钮的对话框
      setEncryptionInfo({ show: true, key: secretKey, algorithm: 'AES-128-CBC' });
      
      console.log('加密维修数据导出成功');
    } catch (error) {
      console.error('导出加密维修数据失败:', error);
      alert('导出失败，请重试');
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4">
          我的维修记录
        </Typography>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <Button
            variant="outlined"
            onClick={exportMaintenanceData}
          >
            导出维修数据
          </Button>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={() => navigate('/report-maintenance')}
          >
            报告异常
          </Button>
        </Box>
      </Box>

      <Grid container spacing={3}>
        {/* 统计卡片 */}
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>待处理</Typography>
              <Typography variant="h3" color="warning.main">
                {maintenanceRecords.filter(r => r.status === 'PENDING').length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>已分配</Typography>
              <Typography variant="h3" color="info.main">
                {maintenanceRecords.filter(r => r.status === 'ASSIGNED').length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>处理中</Typography>
              <Typography variant="h3" color="primary.main">
                {maintenanceRecords.filter(r => r.status === 'IN_PROGRESS').length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>已完成</Typography>
              <Typography variant="h3" color="success.main">
                {maintenanceRecords.filter(r => r.status === 'COMPLETED').length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* 维修记录列表 */}
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                所有维修记录 ({maintenanceRecords.length})
              </Typography>
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>车辆信息</TableCell>
                      <TableCell>异常类型</TableCell>
                      <TableCell>优先级</TableCell>
                      <TableCell>状态</TableCell>
                      <TableCell>服务商</TableCell>
                      <TableCell>报告时间</TableCell>
                      <TableCell>操作</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {maintenanceRecords.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell sx={{ maxWidth: 200 }}>
                          <Box sx={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
                            <Typography variant="subtitle2" sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {record.vehiclePlate}
                            </Typography>
                            <Typography variant="body2" color="text.secondary" sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {record.description}
                            </Typography>
                          </Box>
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={getMaintenanceTypeLabel(record.maintenanceType)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={getPriorityLabel(record.priority)}
                            color={getPriorityColor(record.priority)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={getStatusLabel(record.status)}
                            color={getStatusColor(record.status)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          {record.serviceProviderName || '未分配'}
                        </TableCell>
                        <TableCell>
                          {record.reportedAt ? formatTimestamp(record.reportedAt, 'MM/dd HH:mm') : '未知'}
                        </TableCell>
                        <TableCell>
                          <IconButton
                            onClick={() => handleViewDetails(record)}
                            color="primary"
                          >
                            <VisibilityIcon />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 详情对话框 */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="md" fullWidth>
        <DialogTitle>维修详情</DialogTitle>
        <DialogContent>
          {selectedRecord && (
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>车辆信息</Typography>
                <Typography>{selectedRecord.vehiclePlate}</Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>异常类型</Typography>
                <Typography>{getMaintenanceTypeLabel(selectedRecord.maintenanceType)}</Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>优先级</Typography>
                <Chip
                  label={getPriorityLabel(selectedRecord.priority)}
                  color={getPriorityColor(selectedRecord.priority)}
                  size="small"
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>状态</Typography>
                <Chip
                  label={getStatusLabel(selectedRecord.status)}
                  color={getStatusColor(selectedRecord.status)}
                  size="small"
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>服务商</Typography>
                <Typography>{selectedRecord.serviceProviderName || '未分配'}</Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>报告时间</Typography>
                <Typography>
                  {selectedRecord.reportedAt ? formatTimestamp(selectedRecord.reportedAt, 'yyyy年MM月dd日 HH:mm') : '未知'}
                </Typography>
              </Grid>
              <Grid item xs={12}>
                <Typography variant="subtitle2" gutterBottom>异常描述</Typography>
                <Typography>{selectedRecord.description}</Typography>
              </Grid>
              {selectedRecord.location && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom>发生位置</Typography>
                  <Typography>{selectedRecord.location}</Typography>
                </Grid>
              )}
              {selectedRecord.estimatedCost && (
                <Grid item xs={12} md={6}>
                  <Typography variant="subtitle2" gutterBottom>预估费用</Typography>
                  <Typography>¥{selectedRecord.estimatedCost}</Typography>
                </Grid>
              )}
              {selectedRecord.notes && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom>备注</Typography>
                  <Typography>{selectedRecord.notes}</Typography>
                </Grid>
              )}
              {selectedRecord.tags && selectedRecord.tags.length > 0 && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom>标签</Typography>
                  <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                    {selectedRecord.tags.map((tag, index) => (
                      <Chip key={index} label={tag} size="small" />
                    ))}
                  </Box>
                </Grid>
              )}
            </Grid>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>关闭</Button>
        </DialogActions>
      </Dialog>

      {/* 浮动按钮 */}
      <Fab
        color="primary"
        aria-label="add"
        sx={{ position: 'fixed', bottom: 16, right: 16 }}
        onClick={() => navigate('/report-maintenance')}
      >
        <AddIcon />
      </Fab>

      {/* 加密信息对话框 */}
      <Dialog 
        open={encryptionInfo.show} 
        onClose={handleCloseEncryptionDialog}
        maxWidth="sm" 
        fullWidth
      >
        <DialogTitle>导出成功 - 加密信息</DialogTitle>
        <DialogContent>
          <Box sx={{ mb: 2 }}>
            <Typography variant="subtitle1" gutterBottom>
              加密算法: {encryptionInfo.algorithm}
            </Typography>
            <Typography variant="subtitle1" gutterBottom>
              密钥:
            </Typography>
            <Box sx={{ 
              display: 'flex', 
              alignItems: 'center', 
              p: 1, 
              bgcolor: 'background.default', 
              borderRadius: 1, 
              border: '1px solid', 
              borderColor: 'divider'
            }}>
              <Typography variant="body1" sx={{ flexGrow: 1, wordBreak: 'break-all' }}>
                {encryptionInfo.key}
              </Typography>
              <Button 
                variant="contained" 
                color="primary" 
                size="small" 
                onClick={() => copyToClipboard(encryptionInfo.key)}
                sx={{ ml: 2 }}
              >
                复制密钥
              </Button>
            </Box>
            <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
              请妥善保存此密钥用于解密文件。一旦丢失，无法恢复加密数据！
            </Typography>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseEncryptionDialog} color="primary">
            关闭
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default MyMaintenanceRecords;